package me.dongcha.reggie402.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.dongcha.reggie402.common.BaseContext;
import me.dongcha.reggie402.entity.*;
import me.dongcha.reggie402.mapper.OrdersMapper;
import me.dongcha.reggie402.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartSercive shoppingCartSercive;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void submit(Orders orders) {
        Long userId = BaseContext.getCurrentId();
        String remark = orders.getRemark();
        Integer payMethod = orders.getPayMethod();
        Long addressBookId = orders.getAddressBookId();

        User user = userService.getById(userId);
        AddressBook addressBook = addressBookService.getById(addressBookId);

        String orderId = IdWorker.getId() + "";
        orders.setNumber(orderId);
        LocalDateTime now = LocalDateTime.now();
        orders.setUserId(userId);
        orders.setOrderTime(now);
        orders.setCheckoutTime(now);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartSercive.list(wrapper);

        BigDecimal amount = new BigDecimal(0);
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail, "id");
            orderDetail.setOrderId(Long.parseLong(orderId));
            orderDetails.add(orderDetail);
            BigDecimal fenshu = new BigDecimal(orderDetail.getNumber());
            BigDecimal danjia = shoppingCart.getAmount();
            BigDecimal xiaoji = danjia.multiply(fenshu);
            amount = amount.add(xiaoji);
        }
        orders.setAmount(amount);
        this.save(orders);
        orderDetailService.saveBatch(orderDetails);
        shoppingCartSercive.remove(wrapper);
    }
}
